/* 
 * 	This file is part of VPN Monitor Project 7..

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package monitor.traffic;

import java.util.LinkedList;

import monitor.Monitor;
import monitor.interfaces.InfoDataPackage;
import monitor.interfaces.TrafficStringPackage;
import monitor.utility.Utility;
import monitor.interfaces.EnumTypes.Types;

class TrafficStrings implements TrafficStringPackage{
	private LinkedList<InfoPackage> trafficStrings = null;
	private long logLevel = 0, total = 0, last = 0, time = 0;
	private final Types type;
	private boolean updated = false;
	
	TrafficStrings(Types type){
		this.type = type;
		trafficStrings = new LinkedList<InfoPackage>();
		time = System.nanoTime();
	}
	
	@Override
	public InfoDataPackage getTrafficPackage(){
		return trafficStrings.remove();
	}
	
	@Override
	public int getNumberOfTrafficStrings(){
		return trafficStrings.size();
	}
	
	@Override
	public Types getType() {
		return type;
	}
	
	void changeLogLevel(long logLevel){
		this.logLevel = logLevel;
	}
	
	boolean updated(){
		return updated;
	}
	
	void updateTraffic(long increase){
		updated = false;
		total+=increase;
		if(total-last > logLevel){
			trafficStrings.add(new InfoPackage(total, total-last,(long) ((System.nanoTime() - time)/1e6)));
			last = total;
			time = System.nanoTime();
			updated = true;
		}
	}
	
	/**
	 * Data package for TrafficStrings, contains the average KB/s
	 * between two creations of instances of InfoPackage. The string 
	 * that contains this value also contains total traffic in
	 * GB, MB, kB and/or bytes.
	 */
	private class InfoPackage implements InfoDataPackage{
		private String trafficString = null;
		
		private InfoPackage(long totalTraffic, long trafficPeriod, long time){
			String t = Utility.reportTraffic(totalTraffic, Monitor.TRAFFIC_REPORT_LEVEL);
			trafficString = String.format("%-12s (%.2f KB/s)", t, (double)trafficPeriod/time);
		}
		
		@Override
		public String getTrafficString(){
			return trafficString;
		}
	}
}
